package com.ck567.netty.chatroom.server.handler

import com.ck567.netty.chatroom.message.ChatRequestMessage
import com.ck567.netty.chatroom.message.ChatResponseMessage
import com.ck567.netty.chatroom.server.session.SessionFactory
import com.ck567.netty.chatroom.util.logger
import io.netty.channel.ChannelHandler
import io.netty.channel.ChannelHandlerContext
import io.netty.channel.SimpleChannelInboundHandler

@ChannelHandler.Sharable
class ChatRequestMessageHandler : SimpleChannelInboundHandler<ChatRequestMessage>() {
    override fun channelRead0(ctx: ChannelHandlerContext, msg: ChatRequestMessage) {
        logger.info("================")
        logger.info("发送消息：$msg")
        val to = msg.to
        val channel = SessionFactory.getSession().getChannel(to)

        if (channel != null) {
            channel.writeAndFlush(ChatResponseMessage(msg.from, msg.content))
            logger.info("发送成功！")
        } else {
            ctx.writeAndFlush(ChatResponseMessage(false,"用户不在线或不存在"))
            logger.info("用户不在线或不存在")
        }
    }

    companion object {
        private val logger = logger<ChatRequestMessageHandler>()
    }
}